from abc import ABC, abstractmethod 
import requests
#定义抽象工厂
class SfFactory(ABC):
    @abstractmethod
    def geturl(self):
        pass
    
    @abstractmethod
    def callback(self):
        pass
    
#具体实现工厂
class QQ(SfFactory):

    def geturl(self):
        return 'http://qq.com'
    
    def callback(self):
        return {"name":'','uid':'uid','phone':''}

#具体实现工厂
class Dingding(SfFactory):

    def geturl(self):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://127.0.0.1:8000/user/dingtalkCallback/')}",
            "response_type=code",
            "client_id=dingqxjco4n5jjtt7ctj",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return url
    
    def callback(self,authCode):
        # 根据authCode获取用户accessToken
        data = {
            "clientId": "dingqxjco4n5jjtt7ctj",
            "clientSecret": "cQJnGlcoMmz6Nnv-r0aFEpQAHqiwVK0t4yf1J_9Do8jQP1AV81iVT2M3GXHWLy53",
            "code": authCode,
            "grantType": "authorization_code"
        }
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
     
        name = resp.get('nick')
        uid = resp.get('openId')
        phone = resp.get('mobile')
        return {"name":name,'uid':uid,'phone':phone}
    
#产品类

class Factory():
    def create_factory(self,types):
        if types == 'dinding':
            return Dingding()
        elif types == 'qq':
            return QQ()
        
        
        

#调用方法
# types = 'qq'
factory = Factory()
# fclass = factory.create_factory(types)
# print(fclass.geturl())
